<?php
	App::import('Controller','Eav.AbstractFields');
	class CustomFieldsController extends AbstractFieldsController
	{
		var $name = "CustomFields";
		
		function admin_add()
		{
			$fieldsetId = null;
			$fieldsetModelAlias = low($this->_getFieldModel()->getFieldsetModelAlias());
			if(isset($this->params['named']['fieldset']) && $this->params['named']['fieldset'])
			{
				$fieldsetId = $this->params['named']['fieldset'];
			}
			if(!$fieldsetId)
			{
				$errorMessage = $this->errorMsg(sprintf(__('%s could not be created as %s is not specified.', true),$this->displayName,$fieldsetModelAlias));
				$this->redirect(array('controller'=>"fieldsets",'action'=>"index",'plugin'=>"eav"));
				
			}
			if($this->_getFieldModel()->getFieldsetModel()->hasAny(array('id'=>$fieldsetId)) == false)
			{
				$errorMessage = $this->errorMsg(sprintf(__('Invalid %s specified', true),$fieldsetModelAlias));
				$this->redirect(array('controller'=>"fieldsets",'action'=>"index",'plugin'=>"eav"));
			}
			if($this->data)
			{
				$this->data[$this->fieldModelAlias]['fieldset_id'] = $fieldsetId;
			}		
			parent::admin_add();
			$fieldsetName = $this->_getFieldModel()->getFieldsetModel()->field('name',array('id'=>$fieldsetId));
			$this->pageTitle = sprintf(__('Add a new field in %s'),$fieldsetName);
		}
		
		protected function _afterSave($created = false)
		{
			$this->successMsg(sprintf(__('The %s has been saved', true),$this->displayName));
			$fieldsetId = $this->_getFieldModel()->field('fieldset_id',array('id'=>$this->_getFieldModel()->id));
			$this->redirect(array('action'=>'index','fieldset'=>$fieldsetId));
		}
		
		function admin_edit($id)
		{
			parent::admin_edit($id);
			$this->pageTitle = sprintf(__("Edit %s field"),$this->viewVars['field']['CustomField']['label']);		
		}
		
		function admin_updateOrder($fieldsetId)
		{
			$ordersString = $_POST['orders'];
			$orders = explode('|',$ordersString);
			$i = 1;
			foreach($orders as $fieldId)
			{
				$fieldId = $this->_getFieldModel()->field('id',array('fieldset_id'=>$fieldsetId,'id'=>$fieldId));
				if($fieldId)
				{
					$this->_getFieldModel()->id = $fieldId;
					$this->_getFieldModel()->saveField('order',$i);
					$i++;
				}
			}
			$this->_stop();
		}
		
		function admin_setOrders($fieldsetId)
		{
			$fieldset = $this->_getFieldModel()->getFieldsetModel()->find('first',array('conditions'=>array('id'=>$fieldsetId),'recursive'=>-1));
			$fields = $this->_getFieldModel()->find('all',array('conditions'=>array('fieldset_id'=>$fieldsetId),'order'=>"CustomField.order ASC"));
			$this->pageTitle = sprintf(__("Sort fields of %s"),$fieldset['Fieldset']['name']);
			$this->set(compact('fieldset','fields'));
			
		}
	}
?>